package com.xcity.game.map;

public class MapUtils {
	/**
	 * 已知mapXY求map
	 * @param x mapX
	 * @param y mapY
	 * @return 就是map索引 从0开始
	 */
	public static int mapXY2map(int x, int y){
		int border = getCircleBorder(x, y);
		return mapXY2map(x, y, border);
	}
	
	public static int mapXY2map(int x, int y, int border){
		int m1 = 0;
		int boundary = border * 2 + 1;//1 3 5...
		if(y == border){
			int boundaryUp = boundary * boundary;
			m1 = boundaryUp + x - (boundary >> 1);
		}else if(y == -border){
			int boundaryDown = (boundary - 2) * (boundary - 2);
			m1 = boundaryDown - x + (border) + boundary - 1;
		}else if(x == border){
			int boundaryDown = (boundary - 2) * (boundary - 2);
			m1 = boundaryDown - y + border;
		}else{
			int boundaryUp = boundary * boundary;
			m1 = boundaryUp - ((boundary - 1) << 1) + y + (border);
		}
		return m1 - 1;
	}
	
	
	
	/**
	 * 已知map求mapXY
	 * @param map 从0开始
	 */
	public static int[] map2mapXY(int map){
		int m1 = map + 1;
		int x = 0;
		int y = 0;
		
		int boundaryUp = getCircle(map);//1 2 3 4 5...
		int boundaryDown = 1;
		if(boundaryUp > 1){
			boundaryDown = boundaryUp - 1;
		}
		int upPower = boundaryUp * boundaryUp;
		int downPower = boundaryDown * boundaryDown;
//		int singleBoundary = getSingleCircle(m1);//1 3 5....
		if(boundaryUp % 2 == 0){
			//双数圈	x- y-
			int gap = (upPower - downPower);
			int halfGap = (gap + 1) >> 1;
			if(m1 > downPower + halfGap){
				//x-
				y = -(halfGap >> 1);
				x = downPower + halfGap - y - m1;
			}else{
				//y-
				x = (halfGap >> 1);
				y = downPower + x - m1;
			}
		}else{
			//单数圈 y- x-
			int gap = (upPower - downPower);
			int halfGap = (gap + 1) >> 1;
			if(m1 >= downPower + halfGap){
				//x+
				y = (halfGap >> 1);
				x = m1 - upPower + y;
				}else{
					//y+
					x = -(halfGap >> 1);
					y = m1 - upPower + halfGap - x - 1;
				}
		}
		return new int[]{x, y};
	}
	
	/**
	 * map是在第几圈
	 */
	public static int getCircle(int m0){
		int m1 = m0 + 1;
		if(m1 <= 0){
			return 0;
		}
		int ret = 1;
		while (true) {
			int boundary = ret * ret + 1;
			if(m1 < boundary){
				break;
			}else{
				ret++;
			}
		}
		return ret;
	}
	
	/**
	 * 返回边长
	 */
	public static int getCircleBorder(int x, int y){
		int border = x < 0? -x : x;
		int absY = y < 0? -y : y;
		if(border < absY){
			border = absY;
		}
		return border;
	}
}
